<template>
  <div class="line-gadget-css"
       style="width:100;height:100%"
       :id="id">
    <Portal to="right-disable"
            style="width:100;height:100%"
            v-loading="loading"
            :disabled="!queryModelDefaultSetting.showSetting">
      <DashboardInterceptConsumer :gadgetId="id"
                                  shadow="never"
                                  class="aui-card--fill"
                                  @mouseenter="mouseenter(true)"
                                  @mouseleave="mouseenter(false)"
                                  :style="{height: '100%',border:0}">
        <el-card shadow="never"
                 :style="{height: '100%',border:0}"
                 class="aui-card--fill">
          <div style="width:100%;height:100%;">
            <div class="cardHeader"
                 @mouseenter="mouseenter(true)"
                 @mouseleave="mouseenter(false)"
                 v-if="(widgetName && widgetName.trim().length>0) || (gadgetSetting.headerDescription && gadgetSetting.headerDescription.trim().length>0)">
              <GadgetTitle :gadgetSetting="gadgetSetting"
                           :widgetName="widgetName"></GadgetTitle>
              <MoreMenu :slicer='slicer'
                        :fitToHeight='fitToHeight'
                        :gadgetId='id'
                        :gadgetType='gadgetInfo.com'
                        @updateQuery="query"
                        :widgetName="widgetName"
                        :businessType="gadgetInfo.businessType"
                        :id="gadgetInfo.id"
                        @showQueryModel="showQueryModel"
                        @fullScreen="fullScreen" />

            </div>
            <div class='control-section control-section2'>
              <div class=content-wrapper
                   style="width:'100%';height:100%">
                <div v-if="isHasData" :key="isHasData"
                     style="width:100%;height:100%;">
                     <div style="height:30px;line-height: 30px;font-size:16px;font-weight:700;text-align:center">{{gadgetSetting.title}}</div>
                     <div :id="selfGadgetUuid" style="width:100%;height:calc(100% - 30px);"></div>
                </div>
                <div v-else
                     class="gadget-no-newdata">
                  <div class="widgets-no-data">
                    <div :style="{'fontSize':fontSizeStr1}">{{$t('custom.component.gadget.nodata')}}</div>
                    <!-- <div class="widgets-tip"> <a :href="widgetNoDataWiki"
                         :style="{'fontSize':fontSizeStr2}"
                         target="black">{{$t('custom.component.gadget.nodatatip')}}</a> </div> -->
                  </div>
                </div>
              </div>
            </div>
          </div>
        </el-card>
        <Lastupdatetime v-if="currentTime"
                        :currentTime="currentTime"
                        :linkedDatasetList="linkedDatasetList"
                        :errorStatus="errorStatus"
                        @updateQuery="query()"></Lastupdatetime>
      </DashboardInterceptConsumer>

    </Portal>
    <model :showSetting='queryModelDefaultSetting.showSetting'
           @queryModelClosed='queryModelClosed'
           :dataInfo='queryModelDefaultSetting.dataInfo'
           :updateGadget="upgradeGadgetSetting"
           :slicer='slicer' />
    <DrillThrough :gadgetId='id'
                  :pageId='pageId'
                  :slicer="slicer"
                  :queryId="queryId"
                  ref="drill-through"
                  :widgetName='widgetName' />
  </div>
</template>

<script>
import mixinGadgetViewModule from '@/mixins/gadget-view-module'
import Lastupdatetime from '@/components/last-update-time/index.vue'
import { defaultGadgetSettingList } from '@/utils/data-json'
import mixinFormatViewModule from '@/mixins/format-gadget-view-module'
import * as Echarts from 'echarts'
import ecStat from 'echarts-stat'
import { getUUID, getLeijia, getLeijias } from '@/utils'
import { splitLable, keepDecimalPlaces } from '@/utils/common'
import { debounce, omit } from 'lodash'
import { conditionFunction, conditionData } from '@/utils/widget-condition'
export default ({
  mixins: [mixinGadgetViewModule, mixinFormatViewModule],
  components: {
    Lastupdatetime, model: () => import('@/components/gadget/query-model/query-model')
  },
  data: function () {
    return {
      eChartColor: ['#5470c6', '#91cc75', '#fac858', '#ee6666', '#73c0de', '#3ba272', '#fc8452', '#9a60b4', '#ea7ccc'],
      selfGadgetUuid: getUUID(),
      repeatNumber: 0,
      chartOption: {
        title: {
          text: '',
          left: 'center'
        },
        tooltip: {
          trigger: 'item',
          formatter: '{a}<br />{b}: {c}'
        },
        legend: {
          type: 'scroll',
          top: 20,
          width: '90%',
          data: []
        },
        grid: {
          // top: '11%',
          left: '10px',
          right: '10px',
          bottom: '10px',
          width: '94%',
          // height: '85%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: true,
          data: [],
          axisLabel: {
            rotate: 315,
            formatter: '{value}',
            hideOverlap: true,
            overflow: 'truncate',
            ellipsis: '...'
          },

          name: '',
          nameLocation: 'end',
          nameGap: 5,
          nameRotate: 270
        },
        yAxis: {
          type: 'value',
          axisLabel: {
            formatter: '{value}',
            hideOverlap: true,
            overflow: 'truncate',
            ellipsis: '...'
          },
          name: '',
          nameLocation: 'end',
          nameGap: 10,
          axisLine: {
            show: true
          },
          splitLine: {
            show: false
          },
          axisTick: {
            show: true
          }
        },
        series: []
      },
      chartDom: null,
      currentTime: null,
      queryData: [],
      queryFields: [],
      gadgetSetting: null,
      loading: false,
      chartWidth: '600px',
      queryModelDefaultSetting: {
        showSetting: false,
        dataInfo: {
          businessId: this.pageId,
          gadgetId: this.id,
          gadgetType: 'chartgadget',
          gadgetSetting: this._.find(defaultGadgetSettingList, { gadgetType: 'chartgadget' }).gadgetSetting
        }
      },
      queryId: '',
      queryDrillthrough: {},
      widgetName: '',
      linkedDatasetList: []
    }
  },
  // beforeCreate () {
  //   // this.$options.components.model = () => import('@/components/gadget/query-model/query-model')
  // },
  created () {
    this.gadgetHeight = (this.gadgetInfo.h * 20) - 45
    if(location.pathname.indexOf('bot')!==-1) {
      this.subscribeMessage('runReport', debounce(() => {
      this.query(this.refreshCount > 0 ? 'auto' : false)
      this.refreshCount = this.refreshCount + 1
    }, 2500)) } else {
      this.subscribeMessage('runReport', () => {
      this.query(this.refreshCount > 0 ? 'auto' : false)
      this.refreshCount = this.refreshCount + 1
      })
    }
   
    // this.query()
    this.$store.state.isWidget = false
  },

  updated () {
    if (document.getElementById(`${this.selfGadgetUuid}`) && document.getElementById(`${this.selfGadgetUuid}`).offsetWidth) {
      let wW = document.getElementById(`${this.selfGadgetUuid}`).offsetWidth
      let wH = document.getElementById(`${this.selfGadgetUuid}`).offsetHeight
      this.gadgetSetting.titleFontSize = (parseInt(wW / 70) + parseInt(wH / 200)) < 10 ? '10px' : (parseInt(wW / 70) + parseInt(wH / 200) + 'px')
    }
  },

  methods: {
    updateChart (originData) {
      this.chartDom = document.getElementById(`${this.selfGadgetUuid}`)
      if (!this.chartDom) {
        setTimeout(() => {
          this.repeatNumber++
          this.updateChart(originData)
        }, 1000)
      } else if (!Array.isArray(originData) || (Array.isArray(originData) && originData.length === 0)) {
        Echarts.init(this.chartDom).dispose()
      } else {
        this.repeatNumber = 0
        let myChart = Echarts.init(this.chartDom, this.globalTheme) //canvas 36.74 svg 35.21
        // this.chartOption.title.text = this.gadgetSetting.title
        this.chartOption.title.textStyle = { fontSize: this.gadgetSetting.titleFontSize || 18 }
        // this.chartOption.grid.height = this.gadgetSetting.gridHeight
        // this.chartOption.grid.top = this.gadgetSetting.gridTop
        this.chartOption.xAxis.name = this.gadgetSetting.xName
        this.chartOption.yAxis.name = this.gadgetSetting.yName
        try {
          if (Array.isArray(this.chartOption.yAxis)) {
            this.chartOption.yAxis[0].axisLabel.formatter = (value) => {
              //  return `${(value * 100.00).toFixed(2) + ' %'}`
              if (this.gadgetSetting.yAxisPercentage) {
                return `${keepDecimalPlaces(value, '2', '*', 100)}%`
              } else {
                return `${value}`
              }
            }
          } else {
            this.chartOption.yAxis.axisLabel.formatter = (value) => {
              //  return `${(value * 100.00).toFixed(2) + ' %'}`
              if (this.gadgetSetting.yAxisPercentage) {
                return `${keepDecimalPlaces(value, '2', '*', 100)}%`
              } else {
                return `${value}`
              }
            }
          }
        } catch (error) {

        }
        this.chartOption.xAxis.data = originData.map(e => {
          return e[this.gadgetSetting.valueFieldsNameMeasureX]
        })
        if (this.gadgetSetting.valueFieldsNameManyY && this.gadgetSetting.valueFieldsNameManyY.length > 1) {
          this.chartOption.legend.data = this.gadgetSetting.valueFieldsNameManyY
          let lastList = []
          this.chartOption.legend.data.map(key => {
            const conditionFormat = this.dataInfo.conditionFormat.filter(item => {
              if (item.dataForm.filters.rules.length !== 0) {
                return this._.find(item.dataForm.filters.rules, { key: key  }) || this._.find(item.dataForm.filters.rules, { key: this.gadgetSetting.valueFieldsNameMeasureX  })
              }
            })
            const cloneData = conditionData(this._.cloneDeep(originData), conditionFormat)
            lastList.push({
              name: key,
              type: 'line',
              label: {
                show: true
              },
              data: cloneData.map(item => {
                let obj = {
                  value: item[key],
                  itemStyle: {}
                }
                if (item['format']) {
                  obj.itemStyle.color = item['format'].textColor
                }
                return obj
              })
            })
          })
          if (this.gadgetSetting.isCumulative) {
            lastList.forEach(item => {
              item.data = getLeijias(item.data)
            })
          }
          this.chartOption.series = lastList
          this.chartOption.legend.data = this.chartOption.series.map(e => {
            return e.name
          })

          this.chartOption.xAxis.axisLabel.formatter = (value) => {
            return `${splitLable(this.setFormatFunctionForChart(this.queryFields, value, this.gadgetSetting.valueFieldsNameMeasureX))}`
          }
          this.chartOption.tooltip.formatter = (params) => {
            return `${params.seriesName}: ${this.setFormatFunctionForChart(this.queryFields, params.value, params.seriesName)} <br /> ${this.setFormatFunctionForChart(this.queryFields, params.name, this.gadgetSetting.valueFieldsNameMeasureX)}`
          }
          for (var iii = 0; iii < this.chartOption.series.length; iii++) {
            const element = this.chartOption.series[iii]
            if (element.label && element.label.show) {
              element.label.formatter = (params) => {
                return `${this.setFormatFunctionForChart(this.queryFields, params.value, params.seriesName)}`
              }
            }
          }
          this.chartOption.yAxis.nameLocation = this.gadgetSetting.yAxisNameLocation
          this.chartOption.yAxis.nameGap = this.gadgetSetting.yAxisNameGap
          this.chartOption.yAxis.nameTextStyle = this.gadgetSetting.nameTextStyle
          this.setYMaxMinInterval(this.chartOption)
          if (this.gadgetSetting.showYaxisRight) {
            this.chartOption.xAxis.nameGap = 25
            this.setYaxisRight(this.chartOption)
          }
          this.setSmooth()
          this.setGoal()
          this.axisLabelRotate()
          this.setConnectNulls(this.chartOption)
          this.setLabel(this.chartOption)
          this.chartOption.yAxis.splitLine = { show: false }
          this.chartOption.yAxis.splitLine.show = this.gadgetSetting.splitLineShow
          myChart.setOption(this.chartOption)
          myChart.on('click', params => {
            this.setDrillThroughInfo(params)
          })
          this.$erd.listenTo(this.chartDom, element => {
          this.$nextTick(() => {
            this.resized()
          })
        })
        } else {
          if (this.gadgetSetting.valueFieldsNameMeasureGroup && this.gadgetSetting.valueFieldsNameMeasureGroup !== 'group') {
            let legendList = this._.uniq(originData.map(e => {
              return e[this.gadgetSetting.valueFieldsNameMeasureGroup]
            }))
            this.chartOption.xAxis.data = this._.uniq(originData.map(e => {
              return e[this.gadgetSetting.valueFieldsNameMeasureX]
            }))
            let temp = []
            for (let i = 0; i < legendList.length; i++) {
              const element = legendList[i]
              const conditionFormat = this.dataInfo.conditionFormat.filter(item => {
                if (item.dataForm.filters.rules.length !== 0) {
                  return this._.find(item.dataForm.filters.rules, { key: element  }) || this._.find(item.dataForm.filters.rules, { key: this.gadgetSetting.valueFieldsNameMeasureX  }) || this._.find(item.dataForm.filters.rules, { key: this.gadgetSetting.valueFieldsNameMeasureGroup  })
                }
              })
              const cloneData = conditionData(this._.cloneDeep(originData), conditionFormat)
              var arrList = cloneData.filter(item => {
                return element === item[this.gadgetSetting.valueFieldsNameMeasureGroup]
              })
              let tempData = this.chartOption.xAxis.data.map(e => {
                let dataItem = arrList.find(ee => { return ee[this.gadgetSetting.valueFieldsNameMeasureX] === e })
                let obj = {}
                if (dataItem) {
                  obj.value = dataItem[this.gadgetSetting.valueFieldsNameMeasureY]
                  obj.itemStyle = {}
                  if (dataItem['format']) {
                    obj.itemStyle.color = dataItem['format'].textColor
                  }
                  return obj
                } else {
                  return null
                }
              })
              temp.push({
                name1: `${element}`,
                name: this.setFormatFunctionForChart(this.queryFields, element, this.gadgetSetting.valueFieldsNameMeasureGroup),
                type: 'line',
                label: {
                  show: true
                },
                data: tempData
              })
            }
            delete this.chartOption.legend.data
            // this.chartOption.legend.data = this.setFormatFunctionForChart(this.queryFields, legendList, this.gadgetSetting.valueFieldsNameMeasureGroup)

            this.chartOption.series = temp

            this.chartOption.xAxis.axisLabel.formatter = (value) => {
              return `${splitLable(this.setFormatFunctionForChart(this.queryFields, value, this.gadgetSetting.valueFieldsNameMeasureX))}`
            }
            this.chartOption.tooltip.formatter = (params) => {
              return `${params.seriesName}: ${this.setFormatFunctionForChart(this.queryFields, params.value, this.gadgetSetting.valueFieldsNameMeasureY)} <br /> ${this.setFormatFunctionForChart(this.queryFields, params.name, this.gadgetSetting.valueFieldsNameMeasureX)}`
            }
            for (var ii = 0; ii < this.chartOption.series.length; ii++) {
              const element = this.chartOption.series[ii]
              if (element.label && element.label.show) {
                element.label.formatter = (params) => {
                  return `${this.setFormatFunctionForChart(this.queryFields, params.value, this.gadgetSetting.valueFieldsNameMeasureY)}`
                }
              }
            }
            this.chartOption.yAxis.nameLocation = this.gadgetSetting.yAxisNameLocation
            this.chartOption.yAxis.nameGap = this.gadgetSetting.yAxisNameGap
            this.chartOption.yAxis.nameTextStyle = this.gadgetSetting.nameTextStyle
            this.setYMaxMinInterval(this.chartOption)
            if (this.gadgetSetting.showYaxisRight) {
              this.chartOption.xAxis.nameGap = 25
              this.setYaxisRight(this.chartOption)
            }
            this.setSmooth()
            this.setGoal()
            this.axisLabelRotate()
            this.setConnectNulls(this.chartOption)
            this.setLabel(this.chartOption)
            this.chartOption.yAxis.splitLine = { show: false }
            this.chartOption.yAxis.splitLine.show = this.gadgetSetting.splitLineShow
            myChart.setOption(this.chartOption)
            myChart.on('click', params => {
              params.seriesName = this.chartOption.series[params.seriesIndex].name1
              let findObj = {}
              for (let i = 0; i < originData.length; i++) {
                const element = originData[i]
                let selectList = []
                Object.values(element).forEach(item => {
                  if (params.name === String(item)) {
                    selectList.push(item)
                  }
                  if (params.seriesName === String(item)) {
                    selectList.push(item)
                  }
                  if (selectList.length === 2) {
                    findObj = element
                  }
                })
              }
              params.selectObj = findObj
              this.setDrillThroughInfoMoreDimension(params)
            })
            this.$erd.listenTo(this.chartDom, element => {
              this.$nextTick(() => {
                this.resized()
              })
            })
          } else {
            let tempSeries = [{
              name: this.gadgetSetting.valueFieldsNameMeasureY,
              type: 'line',
              label: {
                show: true
              },
              data: []
            }]
            const key = (Array.isArray(this.gadgetSetting.valueFieldsNameManyY) && this.gadgetSetting.valueFieldsNameManyY.length === 1)
                ? this.gadgetSetting.valueFieldsNameManyY[0]
                : this.gadgetSetting.valueFieldsNameMeasureY
            const conditionFormat = this.dataInfo.conditionFormat.filter(item => {
              if (item.dataForm.filters.rules.length !== 0) {
                return this._.find(item.dataForm.filters.rules, { key: key  }) || this._.find(item.dataForm.filters.rules, { key: this.gadgetSetting.valueFieldsNameMeasureX  })
              }
            })
            originData = conditionData(originData, conditionFormat)
            tempSeries[0].data = originData.map(item => {
              let obj = {
                value: item[key],
                itemStyle: {}
              }
              if (item['format']) {
                obj.itemStyle.color = item['format'].textColor
              }
              return obj
            })
            if (this.gadgetSetting.isCumulative) {
              tempSeries.forEach(item => {
                item.data = getLeijias(item.data)
              })
            }
            this.chartOption.series = tempSeries

            this.chartOption.xAxis.axisLabel.formatter = (value) => {
              return `${splitLable(this.setFormatFunctionForChart(this.queryFields, value, this.gadgetSetting.valueFieldsNameMeasureX))}`
            }
            this.chartOption.tooltip.formatter = (params) => {
              return `${params.seriesName}: ${this.setFormatFunctionForChart(this.queryFields, params.value, params.seriesName)} <br /> ${this.setFormatFunctionForChart(this.queryFields, params.name, this.gadgetSetting.valueFieldsNameMeasureX)}`
            }
            for (var i = 0; i < this.chartOption.series.length; i++) {
              const element = this.chartOption.series[i]
              if (element.label && element.label.show) {
                element.label.formatter = (params) => {
                  return `${this.setFormatFunctionForChart(this.queryFields, params.value, params.seriesName)}`
                }
              }
            }
            this.chartOption.yAxis.nameLocation = this.gadgetSetting.yAxisNameLocation
            this.chartOption.yAxis.nameGap = this.gadgetSetting.yAxisNameGap
            this.chartOption.yAxis.nameTextStyle = this.gadgetSetting.nameTextStyle
            this.setYMaxMinInterval(this.chartOption)
            if (this.gadgetSetting.showYaxisRight) {
              this.chartOption.xAxis.nameGap = 25
              this.setYaxisRight(this.chartOption)
            }
            if (this.gadgetSetting.showTrendLine) {
              var data = []
              originData.forEach((item, index) => {
                data.push([
                  index, Number(item[this.gadgetSetting.valueFieldsNameMeasureY])
                ])
              })
              var temp = this.getRegressionChart(data, '', 'regression-chart', this.gadgetSetting.showTrendLine, 1, myChart)
              this.chartOption.series.push(temp)
            }
            this.setSmooth()
            this.setGoal()
            this.axisLabelRotate()
            this.setConnectNulls(this.chartOption)
            this.setLabel(this.chartOption)
            this.chartOption.yAxis.splitLine = { show: false }
            this.chartOption.yAxis.splitLine.show = this.gadgetSetting.splitLineShow
            console.log(JSON.stringify(this.chartOption))
            myChart.setOption(this.chartOption, !!this.gadgetSetting.showTrendLine)
            myChart.on('click', params => {
              this.setDrillThroughInfo(params)
            })
            this.$erd.listenTo(this.chartDom, element => {
              this.$nextTick(() => {
                this.resized()
              })
            })
          }
        }
      }
    },
    setConnectNulls (val) {
      val.series.forEach(item => {
        item.connectNulls = this.gadgetSetting.connectNulls
        if (this.gadgetSetting.area) {
          val.xAxis.boundaryGap = false
          item.stack = 'Total'
          item.areaStyle = {}
        }
      })
    },
    setLabel (val) {
      val.series.forEach((item, index) => {
        if (item.label) {
          item.label.show = this.gadgetSetting.showlabel
        }
        // if (item.type === 'line' && this.dataInfo.conditionFormat && this.dataInfo.conditionFormat.length > 0) {
        //   item.itemStyle = {
        //     color: (params) => {
        //       return this.valueColorFormat(params.value, params.seriesName, index)
        //     }
        //   }
        // }
      })
    },
    valueColorFormat (val, seriesName, index) {
      let color = null
      const conditionFormat = this.dataInfo.conditionFormat.filter(item => {
        if (item.dataForm.filters.rules.length !== 0) {
          return this._.find(item.dataForm.filters.rules, { key: seriesName  }) || this._.find(item.dataForm.filters.rules, { key: this.gadgetSetting.valueFieldsNameMeasureX  })
        }
      })
      if (conditionFormat) {
        conditionFormat.reverse().map(it => {
          if (it) {
            let str = ''
            it.dataForm.filters.rules.forEach(ii => {
              // eslint-disable-next-line
              if (ii.opt === '==' || ii.opt === '!=') {
                if (!str) {
                  str += `("${(val).toString()}"  ${ii.opt}   "${(ii.value).toString()}")`
                } else {
                  if (it.dataForm.filters.condition === 'and') {
                    str += `&& ("${(val).toString()}"  ${ii.opt}   "${(ii.value).toString()}")`
                  } else {
                    str += `|| ("${(val).toString()}"   ${ii.opt}   "${(ii.value).toString()}")`
                  }
                }
              } else {
                if (!str) {
                  str += (Number(val) + ii.opt + Number(ii.value))
                } else {
                  if (it.dataForm.filters.condition === 'and') {
                    str += `&& (${Number(val)}   ${ii.opt}   ${Number(ii.value)})`
                  } else {
                    str += `|| (${Number(val)}   ${ii.opt}   ${Number(ii.value)})`
                  }
                }
              }
            })
            // eslint-disable-next-line
            let res1 = eval(`${str}`)
            if (res1) {
              color = it.textColor
            }
          }
          // let evalCode = ''
          // if (items.dataForm.filters.rules[0].opt === '==' || items.dataForm.filters.rules[0].opt === '!=') {
          //   evalCode = `'${val}' ${items.dataForm.filters.rules[0].opt} '${items.dataForm.filters.rules[0].value}'`
          // } else {
          //   evalCode = `${Number(val)} ${items.dataForm.filters.rules[0].opt} ${Number(items.dataForm.filters.rules[0].value)}`
          // }
          // // eslint-disable-next-line no-eval
          // if (eval(evalCode)) {
          //   color = items.textColor
          // }
        })
      }

      return color || this.eChartColor[index] || null
    },
    // name age status email
    customiseCell (args) {
      try {
        if (this.isShowCursor) {
          if (args.column.field !== 'dimension1') {
            let res = this.selectFields.find(i => {
              return i.bind === args.column.field
            })
            if (res.dataType) {
              if (res.dataType !== 'dimension') {
                if (typeof args.data[args.column.field] === 'boolean') {
                  args.cell.classList.add('cursor-pointer')
                } else if (Number(args.data[args.column.field]) !== 0) {
                  args.cell.classList.add('cursor-pointer')
                }
              }
            }
          }
        }
      } catch (error) {

      }
      try {
        var arr = this.dataInfo.conditionFormat
        var column = args.column.field
        let res = arr.filter(item => {
          if (item.dataForm.filters.rules.length !== 0) {
            return item.dataForm.filters.rules[0].key === column
          }
        })
        if (args.data) {
          res.reverse().forEach(it => {
            if (it) {
              let str = ''
              it.dataForm.filters.rules.forEach(ii => {
                // eslint-disable-next-line
                var val = args.data[ii.key].toString()
                if (ii.opt === '==' || ii.opt === '!=') {
                  if (!str) {
                    str += `("${(val).toString()}"  ${ii.opt}   "${(ii.value).toString()}")`
                  } else {
                    if (it.dataForm.filters.condition === 'and') {
                      str += `&& ("${(val).toString()}"  ${ii.opt}   "${(ii.value).toString()}")`
                    } else {
                      str += `|| ("${(val).toString()}"   ${ii.opt}   "${(ii.value).toString()}")`
                    }
                  }
                } else {
                  if (!str) {
                    str += (Number(val) + ii.opt + Number(ii.value))
                  } else {
                    if (it.dataForm.filters.condition === 'and') {
                      str += `&& (${Number(val)}   ${ii.opt}   ${Number(ii.value)})`
                    } else {
                      str += `|| (${Number(val)}   ${ii.opt}   ${Number(ii.value)})`
                    }
                  }
                }
              })
              // eslint-disable-next-line
              let res1 = eval(`${str}`)
              if (res1) {
                if (it.entireRow === 'row') {
                  args.cell.dataset.bgc = it.backgroundColor
                  args.cell.dataset.color = it.textColor
                } else {
                  args.cell.style.color = it.textColor ? it.textColor : '#000000'
                  args.cell.style.backgroundColor = it.backgroundColor
                }
              }
            }
          })
        }
      } catch (error) {

      }
    },
    getRegressionChart (chartData, chartTitle, chartId, regType, regOrder, myChart) {
      let regressionDemo = ecStat.regression(regType, chartData, regOrder)
      regressionDemo.points.sort(function (a, b) {
        return a[0] - b[0]
      })

      return {
        name: 'line',
        type: 'line',
        showSymbol: false,
        lineStyle: {
          // type: "dashed",
          color: '#f00'
        },
        data: regressionDemo.points
      }
    },
    axisLabelRotate () {
      this.chartOption.xAxis.axisLabel.rotate = this.gadgetSetting.axisLabelRotate ? Number(this.gadgetSetting.axisLabelRotate) : 0
    },
    setGoal () {
      if (this.gadgetSetting.goal && this.gadgetSetting.goalcolor) {
        this.chartOption.series.unshift({
          data: [Number(this.gadgetSetting.goal)],
          type: 'line',
          silent: true,
          symbolSize: 0,
          markLine: {
            silent: true,
            data: [
              { name: 'Goal', value: Number(this.gadgetSetting.goal), xAxis: 0, yAxis: Number(this.gadgetSetting.goal) }
            ],
            label: {
              position: 'insideStart'
            },
            symbolSize: 0,
            lineStyle: {
              type: 'solid',
              width: 1,
              color: this.gadgetSetting.goalcolor
            }
          }
        })
      }
    },
    setSmooth () {
      if (this.gadgetSetting.smooth) {
        this.chartOption.series.forEach(item => {
          this.$set(item, 'smooth', true)
        })
      }
    },
    setYMaxMinInterval (val) {
      if (val.yAxis instanceof Object) {
        val.yAxis.min = Number(this.gadgetSetting.yAxisValueMin) || null
        val.yAxis.max = Number(this.gadgetSetting.yAxisValueMax) || null
        val.yAxis.interval = Number(this.gadgetSetting.yAxisValueInterval) || null
      }
    },
    setYaxisRight (val) {
      val.series.forEach((item, index) => {
        var res = this.gadgetSetting.useRightyAxis.some(i => i === item.name)
        if (res) {
          item.yAxisIndex = 1
        } else {
          item.yAxisIndex = 0
        }
      })
      if (Array.isArray(val.yAxis)) return
      var temp = val.yAxis
      val.yAxis = []
      val.yAxis.push(temp)
      val.yAxis.push({
        type: 'value',
        name: this.gadgetSetting.YaxisRightLabel,
        min: Number(this.gadgetSetting.yAxismin)?Number(this.gadgetSetting.yAxismin):null,
        max: Number(this.gadgetSetting.yAxismax)?Number(this.gadgetSetting.yAxismax):null,
        position: 'right',
        // axisLabel: {
        //   formatter: '{value}' // 61A0A8
        // },
        axisLabel: {
          formatter: this.gadgetSetting.rightyAxisPercentage ? (value) => {
            return value * 100 + '%'
          } : '{value}' // 61A0A8
        },
        axisLine: {
          lineStyle: {
            color: '#61A0A8'
          }
        },
        nameTextStyle: {
          align: 'right'
        }
      })
    },
    queryModelClosed () {
      this.queryModelDefaultSetting.showSetting = false
      this.query()
    },
    showQueryModel () {
      this.queryModelDefaultSetting.showSetting = true
    },
    resized (i, newH, newW, newHPx, newWPx) {
      setTimeout(() => {
        let myChart = Echarts.init(this.chartDom, this.globalTheme)
        myChart.resize()
      }, 0)
    },
    containerResizedEvent (i, newH, newW, newHPx, newWPx) {
      this.chartWidth = (newWPx - 50) + 'px'
    },
    query (e) {
      // if (this.loading) return
      this.gadgetSetting = this._.merge(this.gadgetSetting, this.queryModelDefaultSetting.dataInfo.gadgetSetting)
      if (e !== 'auto') {
        this.loading = true
      }
      var _self = this
      var obj = JSON.parse(JSON.stringify(this.slicer))
      let tempObj = this.returnReportLinkParam()
      if (tempObj['name'] && this.slicer['name'] && tempObj['name'] === this.slicer['name']) delete this.slicer['name']
      for (var key in obj) {
        if (key === 'id') {
          delete obj.id
        }
      }
      var param = {
        ...obj,
        code: this.code,
        gadgettype: this.wgadgettype,
        widgetName: this.wName,
        slicer: { ...omit(this.slicer, this.slicer.channel_Id && this.slicer.channel_Id.length ? [] : 'channel_Id') },
        pageId: this.pageId,
        gadgetId: this.id,
        filter: this.getFilterStr(),
        type: this.filterType
      }
      this.$interface.reports.getReportDataInfo(param)
        .then(({ data: res }) => {
          _self.verifyHasData(res)
          try {
            _self.dataInfo.conditionFormat = res.conditionFormat
            _self.$parent.$parent.$parent.$parent.$parent.$parent.selectFields = res.selectFields
          } catch (error) {

          }
          if (res.config) {
            if(this._.get(this.dataInfo,'gadgetSetting.dynamic',false)){
              _self.gadgetSetting =  this.dataInfo.gadgetSetting
            }else{
              _self.gadgetSetting = _self._.merge(_self.gadgetSetting, { ...res.config, titleFontSize: undefined })
            }
          }
          if (!_self.gadgetSetting.headerDescription || _self.gadgetSetting.headerDescription === null) {
            _self.gadgetSetting.headerDescription = ''
          }
          let objList = res.selectFields.find(item => { return item.dataType === 'dimension' })
          _self.queryDrillthrough = objList || {}
          _self.queryId = _self.queryDrillthrough ? _self.queryDrillthrough.queryId : ''
          if (res.name) {
            _self.widgetName = res.name 
          } else if (this.wName) {
            _self.widgetName = this.wName
          }  else {
            _self.widgetName = _self.gadgetSetting.headerTitle
          }
          this.fxFields = res.fxFields || []
          if (res.data) {
            _self.updateChart(res.data)
            _self.queryData = res.data
            _self.queryFields = res.selectFields
            _self.linkedDatasetList = res.datasetSync
          }
        }).catch((error) => {
          if (this.wName) {
          this.widgetName = this.wName
        }
          Echarts.init(this.chartDom).dispose()
          this.isHasData = false
          this.loading = false
          if (error.response && error.response.status === 504) {
            this.errorStatus = '504'
            this.gadgetMessageBus.$emit(this.pageId + 'stopautorefresh')
          }
        }).finally(() => {
          _self.currentTime = new Date()
          this.autoRefreshQuery(e)
          this.updateGadgetLoadingStatus(!this.loading)
        })
    }
  }

})
</script>
<style lang="scss" scoped>
.content-wrapper {
  position: relative;
  .gadget-no-newdata {
    position: absolute;
    top: 40%;
    left: 0;
    right: 0;
    margin: 0 auto;
    .widgets-no-data {
      display: flex;
      flex-direction: column;
      align-items: center;
      .widgets-tip {
        margin-top: 5px;
      }
    }
  }
}
</style>
<style scoped>
.el-card ::v-deep .el-card__body {
  padding: 0px !important;
}

.el-card ::v-deep .el-divider--horizontal {
  margin: 3px 0 !important;
}

.threepoints {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.cardHeader {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 6px 20px;
  border-bottom: 1px solid #eee;
  position: relative;
}

.cardTitle {
  font-size: 16px;
  color: #000;
  font-weight: 700;
  display: inline-block;
  max-width: calc(100% - 30px);
  position: relative;
  top: 2px;
}

.cardIcon {
  font-size: 16px;
  font-weight: 600;
  margin-left: 10px;
  position: relative;
  top: -2px;
}
</style>
<style lang="scss">
.line-gadget-css {
  .el-card__body {
    width: 100%;
    height: 100%;
  }
  .control-section2 {
    width: 100%;
    height: calc(100% - 34px);
  }
}
</style>
